<template>
  <div class="app-container">
    <div class="filter-container">
      <el-date-picker
        v-model="date_range"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        style="width: 300px;"
      />
      <el-select v-model="analysis_type" placeholder="分析类型" style="width: 180px;">
        <el-option label="按模块分析" value="module" />
        <el-option label="按操作类型分析" value="operation" />
        <el-option label="按时间分布分析" value="time" />
        <el-option label="按用户分析" value="user" />
      </el-select>
      <el-button type="primary" icon="el-icon-search" @click="handle_analysis">开始分析</el-button>
      <el-button @click="handle_reset">重置</el-button>
    </div>

    <!-- 分析结果展示区域 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="8" animated />
    </div>

    <div v-else-if="analysis_result.length > 0" class="analysis-result">
      <!-- 图表展示 -->
      <div class="chart-container">
        <div class="chart-title">{{ get_chart_title() }}</div>
        <div ref="chart_ref" class="chart" />
      </div>

      <!-- 数据表格 -->
      <el-table
        :data="analysis_result"
        style="width: 100%"
        border
      >
        <el-table-column prop="name" label="名称" />
    <el-table-column prop="count" label="操作次数" />
    <el-table-column prop="percentage" label="占比">
          <template slot-scope="scope">
            {{ scope.row.percentage }}%
          </template>
        </el-table-column>
        <el-table-column label="趋势">
          <template slot-scope="scope">
            <el-progress
              :percentage="scope.row.percentage"
              :color="get_progress_color(scope.row.percentage)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="avg_time" label="平均耗时(ms)" v-if="analysis_type === 'operation'" />
    <el-table-column prop="success_rate" label="成功率" v-if="analysis_type === 'operation'">
          <template slot-scope="scope">
            {{ (scope.row.success_rate * 100).toFixed(2) }}%
          </template>
        </el-table-column>
      </el-table>

      <!-- 统计汇总信息 -->
      <div class="summary-container">
        <el-card>
          <div class="summary-title">统计汇总</div>
          <div class="summary-content">
            <div class="summary-item">
              <span class="summary-label">总操作次数：</span>
              <span class="summary-value">{{ total_count }}</span>
            </div>
            <div class="summary-item" v-if="analysis_type === 'operation'">
              <span class="summary-label">平均响应时间：</span>
              <span class="summary-value">{{ avg_response_time }}ms</span>
            </div>
            <div class="summary-item" v-if="analysis_type === 'operation'">
              <span class="summary-label">总体成功率：</span>
              <span class="summary-value">{{ (total_success_rate * 100).toFixed(2) }}%</span>
            </div>
            <div class="summary-item">
              <span class="summary-label">分析周期：</span>
              <span class="summary-value">{{ format_date_range() }}</span>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <div v-else class="empty-container">
      <el-empty description="暂无分析数据" />
    </div>
  </div>
</template>

<script>
import sysOperationLogApi from '@/api/sys-operation-log'

export default {
  name: 'OperationLogAnalysis',
  data() {
    return {
      loading: false,
      date_range: [new Date(new Date().getTime() - 7 * 24 * 60 * 60 * 1000), new Date()], // 默认近7天
      analysis_type: 'module',
      analysis_result: [],
      total_count: 0,
      avg_response_time: 0,
      total_success_rate: 0,
      chart_instance: null
    }
  },
  mounted() {
    this.handle_analysis() // 初始加载默认分析
  },
  beforeDestroy() {
    // 安全移除事件监听
    window.removeEventListener('resize', this.handle_resize)
    
    // 安全销毁图表实例
    if (this.chart_instance) {
      try {
        this.chart_instance.dispose()
        this.chart_instance = null
      } catch (error) {
        console.error('Error disposing chart instance:', error)
      }
    }
  },
  methods: {
    // 执行分析
    async handle_analysis() {
      if (!this.date_range || this.date_range.length !== 2) {
        this.$message.warning('请选择分析时间范围')
        return
      }

      this.loading = true
      try {
        const params = {
          start_time: this.date_range[0],
          end_time: this.date_range[1],
          type: this.analysis_type
        }

        const { data } = await sysOperationLogApi.analysis(params)
        this.analysis_result = data.list
        this.total_count = data.total_count
        this.avg_response_time = data.avg_response_time || 0
        this.total_success_rate = data.success_rate || 0
        
        // 延迟初始化图表，确保DOM已更新
        setTimeout(() => {
          this.init_chart()
        }, 100)
      } catch (error) {
        this.$message.error('分析失败')
      } finally {
        this.loading = false
      }
    },
    // 重置分析条件
    handle_reset() {
      this.date_range = [new Date(new Date().getTime() - 7 * 24 * 60 * 60 * 1000), new Date()]; // 重置为默认近7天
      this.analysis_type = 'module';
      this.analysis_result = [];
    },
    
    // 初始化图表
    init_chart() {
      const chartDom = this.$refs.chart_ref
      if (!chartDom) return
      
      // 销毁旧实例
      if (this.chart_instance) {
        this.chart_instance.dispose()
      }
      
      // 检查echarts是否可用
      if (!this.$echarts) {
        console.error('echarts is not available')
        return
      }
      
      // 创建新实例
      try {
        this.chart_instance = this.$echarts.init(chartDom)
        
        const option = this.get_chart_option()
        this.chart_instance.setOption(option)
        
        // 响应式调整
        window.addEventListener('resize', this.handle_resize)
      } catch (error) {
        console.error('Failed to initialize echarts:', error)
      }
    },
    
    // 处理窗口大小调整
    handle_resize() {
      if (this.chart_instance) {
        this.chart_instance.resize()
      }
    },
    
    // 获取图表配置
    get_chart_option() {
      const names = this.analysis_result.map(item => item.name)
      const values = this.analysis_result.map(item => item.count)
      
      let chartOption = {
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)'
        },
        series: [
          {
            name: this.get_chart_title(),
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: true,
              formatter: '{b}: {d}%'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 14,
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: true
            },
            data: this.analysis_result.map(item => ({
              value: item.count,
              name: item.name
            }))
          }
        ]
      }
      
      // 时间分布分析使用柱状图
      if (this.analysis_type === 'time') {
        chartOption = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: names,
            axisLabel: {
              interval: 0,
              rotate: 45
            }
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              name: '操作次数',
              type: 'bar',
              data: values,
              itemStyle: {
                color: '#1890ff'
              }
            }
          ]
        }
      }
      
      return chartOption
    },
    
    // 获取图表标题
    get_chart_title() {
      const titles = {
        module: '各模块操作分布',
        operation: '各操作类型分布',
        time: '操作时间分布',
        user: '用户操作分布'
      }
      return titles[this.analysis_type] || '操作日志分析'
    },
    
    // 获取进度条颜色
    get_progress_color(percentage) {
      if (percentage >= 50) return '#67c23a'
      if (percentage >= 20) return '#e6a23c'
      return '#f56c6c'
    },
    
    // 格式化日期范围
    format_date_range() {
      if (!this.date_range || this.date_range.length !== 2) return ''
      const format = date => {
        const d = new Date(date)
        return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
      }
      return `${format(this.date_range[0])} 至 ${format(this.date_range[1])}`
    }
  }
}
</script>

<style scoped>
.filter-container {
  padding: 10px 0;
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}

.loading-container {
  margin-top: 20px;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 4px;
}

.analysis-result {
  margin-top: 20px;
}

.chart-container {
  margin-bottom: 20px;
  background: #fff;
  padding: 15px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.chart-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  text-align: center;
  color: #303133;
}

.chart {
  height: 400px;
}

.empty-container {
  margin-top: 40px;
}

.summary-container {
  margin-top: 20px;
}

.summary-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #303133;
}

.summary-content {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.summary-item {
  display: flex;
  align-items: center;
}

.summary-label {
  color: #606266;
  margin-right: 8px;
}

.summary-value {
  font-size: 18px;
  font-weight: bold;
  color: #1890ff;
}
</style>